enum StorageType {
  LOCAL = 0,
  SESSION = 1
}

interface IStorage {
  getItem<T = any>(key: string): T | undefined
  getItemStr(key: string): string
  setItem(key: string, value: any): void
  removeItem(key: string): void
  clear(): void
}

class WrapStorage implements IStorage {
  storage: Storage
  constructor(isLocal: StorageType) {
    this.storage = isLocal ? sessionStorage : localStorage
  }
  getItem<T = any>(key: string): T | undefined {
    const value = this.storage.getItem(key)
    if (!value) return
    const obj = JSON.parse(value)
    return obj
  }
  getItemStr(key: string): string {
    const val = this.storage.getItem(key)!
    return val
  }
  setItem(key: string, value: any): void {
    const val = JSON.stringify(value)
    this.storage.setItem(key, val)
  }
  removeItem(key: string): void {
    this.storage.removeItem(key)
  }
  clear(): void {
    this.storage.clear()
  }
}

export const tempStorage = new WrapStorage(StorageType.SESSION)
export const lastStorage = new WrapStorage(StorageType.LOCAL)
export default tempStorage
